const express = require('express');
const router = express.Router();
const server = require('../server/userdb')
const jwt = require('../utils/jwt');

router.delete('/deleteUser', async (req, res) => {
    try {
        const result = await server.deleteUser(req.query.id);
        res.send(result)
    } catch (error) {
        res.send(false);
    }

})

router.post('/setAdmin', async (req, res) => {
    try {
        const result = await server.setAdmin(req.body.id);
        res.send(result)
    } catch (error) {
        res.send(false);
    }

})

router.get('/allUsers', async (req, res) => {
    try {
        const result = await server.getAllUsers(req.query.user,req.query.pageNo);
        res.send(result)
    } catch (error) {
        res.send(false);
    }

})

router.get('/pageUsers', async (req, res) => {
    try {
        const result = await server.getPageUsers(req.query.pageNo);
        res.send(result)
    } catch (error) {
        res.send(false);
    }

})

router.post('/login', async (req, res) => {
    try {
        const result = await server.login(req.body.loginid);
        if (!result) {
            return false;
        }
        if (req.body.userpassword === result[0].userpassword) {
            res.send({
                id: req.body.loginid,
                username: result[0].username,
                isLogin: true,
                role:result[0].role,
                token: jwt.publish()
            });
        } else {
            res.send(false);
        }
    } catch (error) {
        res.send(false);
    }



})

router.post('/registe', async (req, res) => {
    try {
        const result = await server.registe(req.body.username, req.body.userpassword)
        res.send(result)
    } catch (error) {
        res.send(false);
    }

})


router.post('/alterPwd', async (req, res) => {
    try {
        const result = await server.alterPwd(req.body.loginid, req.body.oldPwd, req.body.newPwd);
        res.send(result);
    } catch (error) {
        res.send(false)
    }

})
module.exports = router;